<template>
  <div class="addDialogData">
    <el-dialog
      :title="isAdd ? `新建运营位` : '编辑运营位'"
      :visible.sync="addDialogData.isShow"
      width="40%"
    >
      <el-form
        ref="ruleForm"
        :model="ruleForm"
        :rules="rules"
        label-width="200px"
        class="demo-ruleForm"
        style="margin-bottom: 30px"
      >
        <el-form-item label="运营位名称（最多5个字符）" prop="name">
          <el-input
            v-model.trim="ruleForm.name"
            :maxlength="5"
            show-word-limit
            clearable
            :disabled="isCheck"
            style="width: 60%"
            @change="delRemoval"
            placeholder="请输入活动名称"
          ></el-input>
        </el-form-item>
        <el-form-item label="备注" prop="description">
          <el-input
            v-model.trim="ruleForm.description"
            :maxlength="20"
            show-word-limit
            style="width: 60%"
          ></el-input>
        </el-form-item>
        <el-form-item
          v-if="isShowOperationalBelong"
          label="运营位所属"
          prop="operationalBelong"
        >
          <el-select v-model="ruleForm.operationalBelong">
            <el-option
              v-for="item in operationalBelongList"
              :key="item.dictValue"
              :label="item.dictLabel"
              :value="item.dictValue"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-if="isShowGroupType" label="分组人群" prop="groupType">
          <el-radio-group v-model="ruleForm.groupType">
            <el-radio label="ALL">选择全部</el-radio>
            <el-radio label="GROUPING_PEOPLE">选择分组人群</el-radio>
          </el-radio-group>
          <el-button
            v-show="ruleForm.groupType === 'GROUPING_PEOPLE'"
            type="success"
            @click="handleGrouping"
            style="margin-left:10px"
          >
            选择分组
          </el-button>
        </el-form-item>
        <div class="table-box">
          <el-table
            v-loading="loading"
            :data="selectedGroupList"
            style="width: 60%; margin-left:150px"
            v-show="ruleForm.groupType === 'GROUPING_PEOPLE'"
          >
            <el-table-column label="分组名称" prop="name" align="center">
            </el-table-column>
            <el-table-column label="人数" prop="totalNumber" align="center">
            </el-table-column>
            <el-table-column label="计算状态" align="center">
              <template slot-scope="{ row }">
                <span>
                  {{
                    row.finalCalculationStatus
                      | filterName('calculation_status')
                  }}
                </span>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <el-form-item label="运营位图片" prop="imgInfo">
          <uploadSingImg
            :imgUrl="ruleForm.imgInfo"
            accept=".jpg,.jpeg,.png,.gif"
            :maxSize="0.3"
            @getImgUrl="getImgCover"
            :disabled="isCheck"
          >
            <template v-slot:imgInfo
              >（限制上传300KB以内，建议样式：1029X216
              ，只可上传一张）</template
            >
          </uploadSingImg>
        </el-form-item>
        <el-form-item label="类别" prop="redirectType">
          <el-radio-group
            class="radioGroup"
            v-model="ruleForm.redirectType"
            @change="handleChange"
          >
            <el-radio
              v-for="item in urlTypeList"
              :key="item.dictValue"
              :label="item.dictValue"
              >{{ item.dictLabel }}</el-radio
            >
          </el-radio-group>
        </el-form-item>
        <el-form-item
          v-if="ruleForm.redirectType === 'URL'"
          label="详情链接"
          prop="redirectContent"
          key="redirectContent"
        >
          <el-input
            v-model.trim="ruleForm.redirectContent"
            clearable
            :disabled="isCheck"
            style="width: 60%"
            placeholder="请输入详情链接"
          ></el-input>
        </el-form-item>
        <!-- 小程序输入框 -->
        <el-form-item
          v-if="ruleForm.redirectType === 'XCX'"
          label="小程序ID"
          prop="appletId"
        >
          <el-input
            v-model.trim="ruleForm.appletId"
            clearable
            :disabled="isCheck"
            style="width: 60%"
          ></el-input>
        </el-form-item>
        <el-form-item
          v-if="ruleForm.redirectType === 'XCX'"
          label="小程序类型"
          prop="appletType"
        >
          <el-input
            v-model.trim="ruleForm.appletType"
            clearable
            :disabled="isCheck"
            style="width: 60%"
          ></el-input>
        </el-form-item>
        <el-form-item
          v-if="ruleForm.redirectType === 'XCX'"
          label="小程序链接"
          prop="appletPath"
        >
          <el-input
            v-model.trim="ruleForm.appletPath"
            clearable
            :disabled="isCheck"
            style="width: 60%"
          ></el-input>
        </el-form-item>
      </el-form>
      <el-form ref="ruleForms" :inline="true" :model="ruleForm" :rules="rules">
        <el-form-item
          v-if="ruleForm.redirectType === 'APP'"
          label="后续动作"
          prop=""
        >
          <el-select
            v-model="ruleForm.appPath"
            style="width:200px"
            clearable
            placeholder="请选择"
          >
            <el-option
              v-for="item in activesOptions"
              :key="item.dictValue"
              :label="item.dictLabel"
              :value="item.dictValue"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-if="ruleForm.redirectType === 'APP'">
          <el-input
            v-model.trim="ruleForm.data"
            clearable
            :disabled="isCheck"
          ></el-input>
        </el-form-item>
      </el-form>
      <!-- form-footer -->
      <div slot="footer" class="form-footer" style="">
        <el-button type="success" @click="onSubmit('ruleForm')">保存</el-button>
        <el-button size="medium" @click="onCancel">取消</el-button>
      </div>
    </el-dialog>
    <groupCrowdDialog
      v-if="groupCrowdDialogData.isShow"
      :groupCrowdDialogData="groupCrowdDialogData"
      @groupEcho="groupEcho"
    />
  </div>
</template>

<script>
import uploadSingImg from '@common/uploadSingImg' // 上传单个图片公共组件
import { sysNormalDisable } from '@utils/dictionariesFunc'
import groupCrowdDialog from '../../spaceConfiguration/bannerConfigure/groupCrowdDialog'
// 引入接口
import {
  addBusinessManagement,
  getVerifications,
  editBusinessManagement
} from '@/api/businessManagement/index'
import { groupDetail } from '@/api/spaceConfiguration/bannerConfigure'
export default {
  props: ['addDialogData'],
  components: {
    uploadSingImg,
    groupCrowdDialog
  },

  data() {
    var valiAppNmae = (rule, value, callback) => {
      if (this.ruleForm.redirectType === 'URL') {
        let reg = /(http|https):\/\/[-A-Za-z0-9+&@#/%?=~_|!:,.;]+[-A-Za-z0-9+&@#/%=~_|]\S*/
        if (!value) {
          return callback(new Error('详情链接不能为空'))
        } else {
          if (reg.test(value)) {
            callback()
          } else {
            return callback(new Error('请输入正确的详情链接url'))
          }
        }
      }
    }
    const valiGroup = (rule, value, callback) => {
      if (value === 'GROUPING_PEOPLE' && !this.selectedGroupList.length) {
        callback(new Error('请选择分组人群'))
      } else {
        callback()
      }
    }
    return {
      isAdd: true, //是否新增
      isCheck: false, //是否查看
      isEdit: false, //是否编辑
      loading: false,
      isShowOperationalBelong: false, //是否显运营位所属
      isShowGroupType: false, //是否显示人群分组
      // 表单参数
      ruleForm: {
        id: '',
        name: '', //运营位名称
        description: '', // 备注/描述
        imgInfo: '', // 运营位图片
        redirectType: '', // redirectType	跳转类型,可用值:URL,XCX
        // location	展示位置 HOME_PAGE 首页 | MY 我的,可用值:MY,HOME_PAGE
        location: '',
        // urlType:'', //链接类别
        redirectContent: '', //详情链接
        // 小程序字段
        appletId: '',
        appletType: '',
        appletPath: '',
        sort: 0, //展示排序; 默认0
        appPath: '', //APP页面
        operationalBelong: 'MY', //运营位所属
        groupType: 'ALL' //分组人群
      },
      selectedGroupList: [],
      groupCrowdDialogData: {
        isShow: false
      },
      rules: {
        name: {
          required: true,
          message: '您没有填写运营位名称',
          trigger: 'blur'
        },
        imgInfo: [
          { required: true, message: '您没有上传运营位图片', trigger: 'blur' }
        ],
        redirectType: [
          {
            required: true,
            message: '您没有选择类别',
            trigger: ['blur', 'change']
          }
        ],
        redirectContent: [
          {
            required: true,
            message: '详情链接不能为空',
            trigger: 'blur'
          },
          { validator: valiAppNmae, trigger: ['blur', 'change'] }
        ],
        appletId: [
          {
            required: true,
            message: '小程序ID不能为空',
            trigger: 'blur'
          }
        ],
        operationalBelong: [{ required: true }],
        groupType: [{ required: true, validator: valiGroup, trigger: 'change' }]
      },
      // 链接类型
      // 跳转类型,可用值:URL,XCX
      urlTypeList: [
        { dictLabel: 'H5链接', dictValue: 'URL' },
        { dictLabel: '小程序', dictValue: 'XCX' },
        { dictLabel: 'app页面', dictValue: 'APP' }
      ],
      regURL: [
        { required: true, message: '链接不能为空', trigger: 'blur' },
        { validator: valiAppNmae, trigger: ['blur', 'change'] }
      ],
      activesOptions: [],
      operationalBelongList: [
        { dictLabel: '我的', dictValue: 'MY' },
        { dictLabel: '我的发布', dictValue: 'MY_PUBLISH' }
      ]
    }
  },
  computed: {},
  watch: {},
  created() {
    if (this.addDialogData.id === '') {
      this.$set(this.ruleForm, 'redirectType', 'URL')
    }
    if (this.addDialogData.location === 'MY') {
      this.isShowOperationalBelong = true
      this.isShowGroupType = true
    }
  },
  async mounted() {
    this.isAdd = this.addDialogData.id ? false : true
    if (!this.isAdd) {
      // 编辑
      this.id = this.addDialogData.id
      this.params = this.addDialogData.params
      this.getBusinessDetail()
    }
    this.appOperConfJump()
    /* 字典 计算状态 */
    await sysNormalDisable('calculation_status', 'calculation_status')
  },
  methods: {
    getBusinessDetail() {
      this.$set(this.ruleForm, 'imgInfo', this.params.imgJson)
      this.ruleForm = { ...this.params }
      const groupType = this.ruleForm.groupThrong ? 'GROUPING_PEOPLE' : 'ALL'
      this.$set(this.ruleForm, 'groupType', groupType)
      if (this.ruleForm.groupThrong) {
        groupDetail([this.ruleForm.groupThrong], (res) => {
          this.selectedGroupList = res
        })
      }
      if (this.ruleForm.redirectType === 'XCX') {
        let redirectContent = JSON.parse(this.params.redirectContent)
        this.$set(this.ruleForm, 'appletId', redirectContent.appletId)
        this.$set(this.ruleForm, 'appletType', redirectContent.appletType)
        this.$set(this.ruleForm, 'appletPath', redirectContent.appletPath)
      }
      if (this.ruleForm.redirectType === 'APP') {
        let redirectContent = JSON.parse(this.params.redirectContent)
        this.$set(this.ruleForm, 'appPath', redirectContent.redirectPage)
        this.$set(this.ruleForm, 'data', redirectContent.params)
      }
    },
    // 活动名称去重
    delRemoval(val) {
      // 判断有值的情况才请求后台接口
      if (val) {
        getVerifications(this.addDialogData.location, val, (res) => {
          if (res) {
            this.$message.error('运营位名称重复!!!请重新填写或修改')
          }
        })
      }
    },
    // 运营位图片
    getImgCover(url) {
      this.$set(this.ruleForm, 'imgInfo', url)
    },
    handleChange(val) {
      if (val === 'URL') {
        this.$set(this.ruleForm, 'redirectContent', '')
      }
    },
    /* 选择分组 */
    handleGrouping() {
      this.groupCrowdDialogData.isShow = true
    },
    /* 分组列表 */
    groupEcho(val) {
      this.selectedGroupList = []
      this.selectedGroupList.push(val)
      this.$refs['ruleForm'].clearValidate('groupType')
    },
    // 提交功能
    onSubmit(formName) {
      let addActivesss
      this.$refs[formName].validate((valid) => {
        addActivesss = valid
        if (!valid) {
          this.$message.warning('请检查必填项')
        } else {
          // this.loading = true
          this.$set(this.ruleForm, 'location', this.addDialogData.location)
          if (this.ruleForm.groupType === 'ALL') {
            this.ruleForm.groupThrong = ''
          } else {
            this.ruleForm.groupThrong = this.selectedGroupList[0].id
          }
          if (this.ruleForm.redirectType === 'XCX') {
            this.ruleForm.redirectContent = {
              appletId: this.ruleForm.appletId,
              appletType: this.ruleForm.appletType,
              appletPath: this.ruleForm.appletPath
            }
            this.ruleForm.redirectContent = JSON.stringify(
              this.ruleForm.redirectContent
            )
          } else if (this.ruleForm.redirectType === 'APP') {
            this.ruleForm.redirectContent = {
              redirectPage: this.ruleForm.appPath,
              params: this.ruleForm.data
            }
            this.ruleForm.redirectContent = JSON.stringify(
              this.ruleForm.redirectContent
            )
          } else {
            this.ruleForm.redirectContent = this.ruleForm.redirectContent
          }

          delete this.ruleForm.appletId
          delete this.ruleForm.appletType
          delete this.ruleForm.appletPath
          delete this.ruleForm.apptPath
          delete this.ruleForm.data
          let params = {
            id: this.ruleForm.id, //运营位id
            name: this.ruleForm.name, // 运营位名称
            description: this.ruleForm.description, // 备注/描述
            imgInfo: this.ruleForm.imgInfo, // 运营位图片
            redirectType: this.ruleForm.redirectType, //跳转类型
            redirectContent: this.ruleForm.redirectContent, //跳转内容
            location: this.addDialogData.location,
            sort: this.ruleForm.sort,
            groupThrong: this.ruleForm.groupThrong,
            operationalBelong: this.ruleForm.operationalBelong
          }
          if (this.ruleForm.id === '') {
            delete this.ruleForm.id
            // 新增
            addBusinessManagement(this.ruleForm, (res) => {
              this.addDialogData.isShow = false
              this.loading = false
              this.$emit('refresh')
              this.onCancel()
            })
          } else {
            editBusinessManagement(this.ruleForm.id, params, (res) => {
              this.addDialogData.isShow = false
              this.loading = false
              this.$emit('refresh')
              this.onCancel()
            })
          }
        }
      })
    },
    // 取消功能
    onCancel() {
      // 关闭前清空
      this.addDialogData.id = null
      // 清空form
      this.$refs['ruleForm'].resetFields()
      // 关闭弹窗
      this.addDialogData.isShow = false
    },
    async appOperConfJump() {
      let active = await sysNormalDisable(
        'app_oper_conf_jump',
        'app_oper_conf_jump'
      )
      let activeObj = [
        {
          dictValue: '',
          dictLabel: '全部'
        }
      ]
      this.activesOptions = activeObj.concat(active)
    }
  }
}
</script>

<style lang="less" scoped>
.addDialogData {
  margin: 20px auto;
}
:deep(.el-dialog .el-dialog__body) {
  padding: 25px 30px 25px 20px;
}

.red {
  color: red;
  margin-left: 21%;
  margin-bottom: 15px;
}
</style>
